import datetime
from sqlalchemy.ext.associationproxy import association_proxy

from cibynet.model import meta
from cibynet.model import utils


class MachineIp(utils.ObjectHavingIp):
  """Association between machine and ip.
  """
  
  def _get_to_date(self):
    """Returns date when the relation has ended (or it supposed to).
    """
    return self._to_date
  
  def _set_to_date(self, value):
    """End the relation between a machine and an ip, set the correspondind date.
    
    Arguments:
      - value: when stops the relation.
    """
    # To make the ip available, we need to be sure it is not used any more.
    if value:
      assert value <= datetime.datetime.now()
      self._ip.available = True
    self._to_date = value
    
  def _del_to_date(self):
    """Forbidden.
    """
    assert False
    
  to_date = property(_get_to_date, _set_to_date, _del_to_date)
  
  def __init__(self, machine=None, ip=None, from_date=None, to_date=None):
    """This is intended to be used by the associaton proxy of sqlalchemy.
    Either the attribute machine or ip is already set, 
    the other one is provided.
    """
    assert not machine or not ip
    if machine: self.machine = machine
    if ip: self.ip = ip
    self.from_date = from_date or datetime.datetime.now()
    self.to_date = to_date
    
    def __repr__(self):
      return "<Machine-ip association %s %s (from %s to %s)>" % \
          (self.machine, self.ip, self.from_date, self.to_fate)
    